<?php

jimport('joomla.application.component.controller');

class bgController extends JController {
    public function __construct(){
        parent::__construct();
          
        $this->model = $this->getModel();
    }
    
    public function display($cachable = false, $urlparams = false) {
        parent::display($cachable, $urlparams);
    }
    
    //save download collection
    public function save(){
        $data = &JRequest::getVar('jform');
        $err = '';
        if(empty($data['DOWI_NAME'])){
            //$err .= "VUI LONG NHAP TEN TAP TIN";
            $err .= "ファイル名を記入してください。";
            
        }else{
            //get filename
            $data['DOWI_PATH']=$_POST['jformDOWI_PATH'];

            /*if(!empty($_FILES['jformDOWI_PATH']['name'])){
                $data['DOWI_PATH'] = $_FILES['jformDOWI_PATH']['name'];
                
                //get size, extension
                $file_size = $_FILES['jformDOWI_PATH']['size'];
                $file_type = end(explode('.', $_FILES['jformDOWI_PATH']['name']));
                
                //get upload config
                $config = HelperBG::getUploadConfig();
                $config_size = $config['size'];
                $config_type = explode(',',$config['type']);
                
                //check size and extension
                if($file_size <= $config_size){
                    if(!$this->invalidExtension($config_type,$file_type)){
                        $err .= "アップロードするファイルが正しくありません。";
                    }
                }else{
                    $err .= "ファイルサイズが許容サイズを過ぎています。";
                }
                
            }else{
                //$err .= "VUI LONG CHON TAP TIN DINH KEM";
                $err .= "添付ファイルを選択してください。";
                
            }*/
        }
        if(!$err){
            
            //get id for DOWI_USEM_CODE
            $user = JFactory::getUser();
            $data['DOWI_USEM_CODE'] = $user->get('id');
            

            /*$config = HelperBG::getUploadConfig();
            
            $config_size = $config['size'];
            $mb = $config_size/1048576;

            //add file size in description
                                   
            $file_size = $_FILES['jformDOWI_PATH']['size'];
            if(!empty($file_size)){
                $mb = $file_size/1048576; $mb = round($mb,1);
                $data['DOWI_DESCRIPTION'] = $data['DOWI_DESCRIPTION']." $mb"."MB";
            }*/

            //get file size
            //if(isset($file_size)){$file_size = $config_size;
            
                //$data['DOWI_DESCRIPTION'] .= $file_size." MB";
            //}
            
            //get date now
            $now = getdate(); 
            $currentTime = $now["hours"] . ":" . $now["minutes"] . ":" . $now["seconds"]; 
            $currentDate =  $now["year"] . "." . $now["mon"] . "." . $now["mday"]; 
            $date = $currentDate." ".$currentTime;
            $data['DOWI_DATE'] = $date;
        
            if($this->model->savedownload($data)){
                
                /*$encodeDOWI_PATH = sha1($_FILES['jformDOWI_PATH']['name']);
                
                //upload file
                if(!empty($_FILES['jformDOWI_PATH']['name'])){
                    move_uploaded_file($_FILES['jformDOWI_PATH']['tmp_name'],"uploads/files/com_download/" . $encodeDOWI_PATH);    
                }*/
                    
                //$this->setRedirect('index.php?option=com_download');
                $message = "データを追加しました。";
                JRequest::setVar('task','');
                JFactory::getApplication()->enqueueMessage($message, 'message');
                
            }else{
                //JError::raiseError(500, 'Error ! Can\'t save download collection' );
                //$error = "Error! Can't save!";
                $error = "エラー！データが記録されません。";
                JRequest::setVar('task','');
                JFactory::getApplication()->enqueueMessage($error, 'error');
            }
        }else{
            JRequest::setVar('task','error');
            JFactory::getApplication()->enqueueMessage($err, 'error');
        }
        
        parent::display();
    }
    //check file extension
    public function invalidExtension($arr,$extension){
        foreach($arr as $value){
            if($value == $extension){
                return true;
            }
        }
        return false;
    }
    //remove download collection
    public function remove(){
    	$cid = JRequest::getVar('cid');
                
        foreach($cid as $value){
            //get DOWI_PATH
            $dowi_path = $this->getModel()->getDowi_PathFromID($value);
            //Del DOWI_PATH file
            if($dowi_path != null){
                
                $encodeDOWI_PATH = sha1($dowi_path);
                
                $path = "uploads/files/com_download/$encodeDOWI_PATH";
                if(file_exists($path)){
                    $del = unlink($path);
                }
            }
        }
           
        if($this->model->remove($cid)){
            //$this->setRedirect('index.php?option=com_download');
            $message = "データを削除しました。";
            JRequest::setVar('task','');
            JFactory::getApplication()->enqueueMessage($message, 'message');
        }else{
            //JError::raiseError(500, 'Error ! Can\'t delete' );
            $error = "エラー！データが削除されません。";
            JRequest::setVar('task','');
            JFactory::getApplication()->enqueueMessage($error, 'error');
        }
        
        parent::display();
    }
    
    //show add cadm display
    public function addCadm(){
        
        $id_Max = $this->getModel()->getMaxCADM_CODE();
                
        echo '<div class="m" style="overflow: hidden;margin-bottom:10px;">
                <div  webmemes_parsed="1">
                 <span class="float-left button" style="line-height: 55px; font-weight:bold;">カテゴリダウンロード作成</span>
        			<div webmemes_parsed="1">
        				<div class="toolbar-list" id="toolbar" webmemes_parsed="1">
                                            
                                <ul>
                                    <li class="button" id="toolbar-save">
                                        <a href="#" id="link_save" class="toolbar">
                                        <span class="icon-32-save" webmemes_parsed="1">
                                        </span>
                                        登録
                                        </a>
                                    </li>
                                    
                                    <li class="button" id="toolbar-cancel">
                                        <a href="#" id="link_cancel" class="toolbar">
                                        <span class="icon-32-cancel" webmemes_parsed="1">
                                        </span>
                                        キャンセル
                                        </a>
                                    </li>                                
                                </ul>
                                
                        </div>
                                					
        			</div>
        	</div>
            </div>
            <div class="clr"> </div>';
        echo '<table>
                <tr>
                    <td width="210px"><label>カテゴリダウンロードコード</label></td>
                    <td><input type="text" name="CADM_CODE" id="CADM_CODE" readonly="true" value="'.++$id_Max.'" class="inputbox medium" style="width:230px" /></td>
                </tr>
                <tr>
                    <td><label>カテゴリダウンロード名</label></td>
                    <td><input type="text" name="CADM_NAME" id="CADM_NAME" class="inputbox medium" style="width:230px" /></td>
                </tr>
             </table>';
        
        echo '<script>
                jq(document).ready(function() {        
                //save
                jq("#link_save").click(function(){
                        jq.ajax({';
        echo  "            url: 'index.php?option=com_download&task=saveCadm'
                            +'&CADM_CODE='+jq('#CADM_CODE').val()+'&CADM_NAME='+encodeURI(jq('#CADM_NAME').val())+'&addNew=1',
                          context: document.body
                        }).done(function(data ) {
                          jq('#cadm_content').html(data);
                        }); 
                })";
        echo '  //save
                jq("#link_cancel").click(function(){
                        jq.ajax({';
        echo  "            url: 'index.php?option=com_download&task=searchCadm',
                          context: document.body
                        }).done(function(data ) {
                          jq('#cadm_content').html(data);
                        }); 
                })
            });    
            </script>";
        
        $app = &JFactory::getApplication();
        $app->close();
    }
    //show edit cadm display
    public function editCadm(){
        
        $id = JRequest::getVar('CADM_CODE');
        $result = $this->getModel()->getCadmFromID($id);
        
        echo '<div class="m" style="overflow: hidden;margin-bottom:10px;">
                <div  webmemes_parsed="1">
                 <span class="float-left button" style="line-height: 55px; font-weight:bold;">カテゴリダウンロード更新</span>
        			<div webmemes_parsed="1">
        				<div class="toolbar-list" id="toolbar" webmemes_parsed="1">
                                            
                                <ul>
                                    <li class="button" id="toolbar-save">
                                        <a href="#" id="link_save" class="toolbar">
                                        <span class="icon-32-save" webmemes_parsed="1">
                                        </span>
                                        登録
                                        </a>
                                    </li>
                                    
                                    <li class="button" id="toolbar-cancel">
                                        <a href="#" id="link_cancel" class="toolbar">
                                        <span class="icon-32-cancel" webmemes_parsed="1">
                                        </span>
                                        キャンセル
                                        </a>
                                    </li>                                
                                </ul>
                                
                        </div>
                                					
        			</div>
        	</div>
            </div>
            <div class="clr"> </div>';
        echo '<table>
                <tr>
                    <td width="210px"><label>カテゴリダウンロードコード</label></td>
                    <td><input type="text" name="CADM_CODE" id="CADM_CODE" readonly="true" value="'.$result->CADM_CODE.'" style="width:230px" class="inputbox medium" /></td>
                </tr>
                <tr>
                    <td><label>カテゴリダウンロード名</label></td>
                    <td><input type="text" name="CADM_NAME" id="CADM_NAME" value="'.$result->CADM_NAME.'" class="inputbox medium" style="width:230px" /></td>
                </tr>
             </table>';
        
        echo '<script>
                jq(document).ready(function() {        
                //save
                jq("#link_save").click(function(){
                        jq.ajax({';
        echo  "            url: 'index.php?option=com_download&task=saveCadm'
                            +'&CADM_CODE='+encodeURI(jq('#CADM_CODE').val())+'&CADM_NAME='+encodeURI(jq('#CADM_NAME').val())+'&addNew=0',
                          context: document.body
                        }).done(function(data ) {
                          jq('#cadm_content').html(data);
                        }); 
                })";
        echo '  //save
                jq("#link_cancel").click(function(){
                        jq.ajax({';
        echo  "            url: 'index.php?option=com_download&task=searchCadm',
                          context: document.body
                        }).done(function(data ) {
                          jq('#cadm_content').html(data);
                        }); 
                })
            });    
            </script>";
        
        $app = &JFactory::getApplication();
        $app->close();
    }
    //save cadm
    public function saveCadm(){
        $data['CADM_CODE'] =  JRequest::getVar('CADM_CODE');
        $data['CADM_NAME'] = JRequest::getVar('CADM_NAME');
        $addNew = JRequest::getVar('addNew');
        if($addNew==1){
            $addNew = true;
        }else{
            $addNew = false;
        }
        if($this->model->savecadm($data,$addNew)){
            $this->searchCadm();
        }else{
            echo "Can't save!";
        }
        
        $app = &JFactory::getApplication();
        $app->close();
    }
    //delete cadm
    public function deleteCadm(){
        
        $cid = JRequest::getVar('cid');
        $cid = substr($cid,1);  
        if($this->model->removeCadm($cid)){
            $this->searchCadm();        
        }else{
            echo "Error!!!";
        }
        
        $app = &JFactory::getApplication();
        $app->close();
    }
    
    //show list cadm
    public function searchCadm(){
        
        $list_cadm = $this->model->getAllCadmPopup();
        
        echo '<div class="m" style="overflow: hidden;"> 
                <div  webmemes_parsed="1">
                 <span class="float-left button" style="line-height: 55px; font-weight:bold;">カテゴリダウンロード一覧管理</span>
        			<div webmemes_parsed="1">
        				<div class="toolbar-list" id="toolbar" webmemes_parsed="1">
                                            
                            <ul>
                                <li class="button" id="toolbar-new">
                                    <a href="#" id="link_add" class="toolbar">
                                    <span class="icon-32-new" webmemes_parsed="1">
                                    </span>
                                    作成
                                    </a>
                                </li>
                                
                                <li class="button" id="toolbar-edit">
                                    <a href="#" id="link_edit" class="toolbar">
                                    <span class="icon-32-edit" webmemes_parsed="1">
                                    </span>
                                    編集
                                    </a>
                                </li>
                                
                                <li class="button" id="toolbar-delete">
                                    <a href="#" id="link_delete" class="toolbar">
                                    <span class="icon-32-delete" webmemes_parsed="1">
                                    </span>
                                    削除
                                    </a>
                                </li>
                            
                            </ul>
                                
                        </div>
                                					
        			</div>
        	</div>
            </div>
            <div class="clr"> </div>
            
            <div class="m" style="overflow: hidden; margin-top: 10px;">
            <div id="the_wrap">
                <div class="the_scroll">
                   <table class="adminlist">
                		<thead>
                			<tr>
                				<th class="th10">
                					<input type="checkbox" name="checkall-toggle" value="" title="Check All" onclick="checkAll(this)"/>
                                </th>
                                <th class="th30">
                                    ID
                                </th>
                                <th class="th60">
                                    ダウンロードカテゴリ名
                                </th>
                				
                			</tr>
                		</thead>
                                		
                		<tbody>';
                           
                            if($list_cadm != null){
                                foreach($list_cadm as $k=>$row){
                                         
                    	echo  '<tr class="row'.($k%2).'">
                    			<td class="center">
                                    <input type="checkbox" class="checkbox-id"  id="cb'.$row->CADM_CODE.'" name="cid[]" value="'. $row->CADM_CODE.'" onclick="isChecked('.$row->CADM_CODE.');" />
                                </td>
                                <td class="text-algin-left"><a href="#" class="item_edit" onclick="jq('."'#cadm_code_temp'".').val('.$row->CADM_CODE.')" >'. $row->CADM_CODE.'</a></td>
                                <td class="text-algin-left"><a href="#" class="item_edit" onclick="jq('."'#cadm_code_temp'".').val('.$row->CADM_CODE.')" >'. $row->CADM_NAME.'</a></td>
                    			
                    		  </tr>';
                            
                                }
                            }else{
                            
                        echo    '<tr>
                                    <td class="center" colspan="3">データは見つかりませんでした。</td>
                                </tr>';
                                
                            }
                         
           echo     	'</tbody>
                       
                	</table>
                    <input type="hidden" id="cadm_code_temp" value="" />
                    <input type="hidden" name="boxchecked" id="boxchecked" value="0"/>
                </div>
            </div>
            </div>';
        echo '<script>
                function checkAll(a,b){b||(b="cb");if(a.form){for(var c=0,d=0,f=a.form.elements.length;d<f;d++){var e=a.form.elements[d];if(e.type==a.type&&(b&&0==e.id.indexOf(b)||!b))e.checked=a.checked,c+=!0==e.checked?1:0}if(a.form.boxchecked)a.form.boxchecked.value=c;return!0}for(var e=document.adminForm,c=e.toggle.checked,f=a,g=0,d=0;d<f;d++){var h=e[b+""+d];if(h)h.checked=c,g++}document.adminForm.boxchecked.value=c?g:0}';
        echo "  function isChecked(a){ if(document.id('cb'+a).checked==true){document.id('boxchecked').value++;}else{document.id('boxchecked').value--;}};";
                
        echo '    jq(document).ready(function() {
                            
                    //add
                    jq("#link_add").click(function(){
                        
                            jq.ajax({';
        echo "                 url: 'index.php?option=com_download&task=addCadm',
                              context: document.body
                            }).done(function(data ) {
                              jq('#cadm_content').html(data);
                            }); 
                    });";
                    
        echo '       //edit
                    jq("#link_edit").click(function(){';
        echo "          if(document.id('boxchecked').value==0){
                            alert('編集対象のものを指定してから行ってください。');
                            return false;
                        }  
                        jq( '.checkbox-id' ).each(function() {
                            if(jq(this).attr('checked')){
                                id = jq(this).val();             
                            }
                        });
                        //ajax
                        jq.ajax({
                          url: 'index.php?option=com_download&task=editCadm'
                          +'&CADM_CODE='+id,
                          context: document.body
                        }).done(function(data ) {
                          jq('#cadm_content').html(data);
                        }); 
                    });";
        echo '      //load edit display when click cadm_code
                    jq(".item_edit").live("click",function(){
                        var id = jq("#cadm_code_temp").val();
                        //ajax
                        jq.ajax({';
        echo "            url: 'index.php?option=com_download&task=editCadm'
                          +'&CADM_CODE='+id,
                          context: document.body
                        }).done(function(data ) {
                          jq('#cadm_content').html(data);
                        });
                    });";
        echo '      //delete
                    jq("#link_delete").click(function(){';
        echo "              if (document.id('boxchecked').value==0){
                            alert('編集対象のものを指定してから行ってください。');
                            return false;
                        }
                        if(!confirm('選択たのを削除します。よろしいでしょうか？')){
                            return false;
                        }
                        var list_id = '';
                        jq( '.checkbox-id' ).each(function() {
                            if(jq(this).attr('checked')){
                                list_id += ','+jq(this).val();             
                            }
                        });
                        if(list_id != ''){
                            //ajax
                            jq.ajax({
                              url: 'index.php?option=com_download&task=deleteCadm'
                              +'&cid='+list_id,
                              context: document.body
                            }).done(function(data ) {
                              jq('#cadm_content').html(data);
                            });
                        }
                    });
                    
                    
                });
                  
            
            </script>";
        
        $app = &JFactory::getApplication();
        $app->close();
    }
    
    
    public function loadCadm(){
        $cadm_current = JRequest::getVar('cadm_current');
        
        $model = $this->getModel();
        $list_cadm = $model->getAllCadm();
        
        echo '<select class="input_large" name="jform[DOWI_CADM_CODE]" id="jformDOWI_CADM_CODE">';
                    
                foreach($list_cadm as $value){
                   echo   '<option value="'. $value->CADM_CODE. '"'; if($value == $cadm_current){ echo 'selected="selected"'; } echo '>'; echo $value->CADM_NAME; echo '</option>';
                }
                    
        echo  '</select>';
        
        
        $app = &JFactory::getApplication();
        $app->close();
        exit();
    }

}